<template>
  <view class="login-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <!-- 顶部区域：LOGO和品牌名 -->
    <view class="header-section">
      <view class="brand-container">
        <image class="logo" src="/static/logo.png?v=1" mode="aspectFit"></image>
        <text class="brand-name">恒通云</text>
        <text class="brand-slogan">化工智能管理系统</text>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 登录选项卡 -->
      <view class="tab-wrapper">
        <view class="tab-header">
          <view
            class="tab-item"
            :class="{ active: currentTab === 'account' }"
            @click="switchTab('account')"
          >
            <uni-icons type="person" size="18" color="#ffffff"></uni-icons>
            <text class="tab-text">账号登录</text>
          </view>
          <view
            class="tab-item"
            :class="{ active: currentTab === 'sms' }"
            @click="switchTab('sms')"
          >
            <uni-icons type="phone" size="18" color="#ffffff"></uni-icons>
            <text class="tab-text">短信登录</text>
          </view>
        </view>
      </view>

      <!-- 登录表单区域 -->
      <view class="form-container">
        <!-- 账号密码登录 -->
        <view v-if="currentTab === 'account'" class="login-form">
          <view class="input-group">
            <uni-easyinput
              v-model="accountForm.Account"
              placeholder="请输入用户名"
              prefixIcon="person"
              :clearable="false"
              class="glass-input"
              trim
            />
          </view>

          <view class="input-group">
            <uni-easyinput
              v-model="accountForm.Password"
              type="password"
              placeholder="请输入密码"
              prefixIcon="locked"
              :clearable="false"
              :passwordIcon="true"
              class="glass-input"
            />
          </view>

          <view class="input-group">
            <uni-easyinput
              v-model="accountForm.Tenant"
              placeholder="请输入租户号（可选）"
              prefixIcon="home"
              :clearable="false"
              class="glass-input"
              trim
            />
          </view>

          <view class="submit-section">
            <view
              class="primary-button"
              :class="{ 'primary-button--loading': accountLoading }"
              @click="handleAccountLogin"
            >
              <text class="button-text">
                {{ accountLoading ? "登录中..." : "账号登录" }}
              </text>
              <view v-if="!accountLoading" class="button-shine"></view>
            </view>
          </view>
        </view>

        <!-- 短信验证登录 -->
        <view v-if="currentTab === 'sms'" class="login-form">
          <view class="input-group">
            <uni-easyinput
              v-model="smsForm.Mobile"
              type="number"
              :maxlength="11"
              placeholder="请输入手机号"
              prefixIcon="phone"
              :clearable="false"
              class="glass-input"
            />
          </view>

          <view class="input-group">
            <view class="sms-input-wrapper">
              <uni-easyinput
                v-model="smsForm.Code"
                type="number"
                :maxlength="6"
                placeholder="请输入验证码"
                prefixIcon="auth"
                :clearable="false"
                class="glass-input sms-input"
              />
              <view
                class="sms-button"
                :class="{
                  'sms-button--disabled': smsLoading || countdown > 0,
                }"
                @click="sendSms"
              >
                <text class="sms-button-text">
                  {{
                    smsLoading
                      ? "发送中"
                      : countdown > 0
                        ? `${countdown}s`
                        : "获取验证码"
                  }}
                </text>
              </view>
            </view>
          </view>

          <view class="submit-section">
            <view
              class="primary-button"
              :class="{ 'primary-button--loading': smsLoginLoading }"
              @click="handleSmsLogin"
            >
              <text class="button-text">
                {{ smsLoginLoading ? "登录中..." : "短信登录" }}
              </text>
              <view v-if="!smsLoginLoading" class="button-shine"></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 其他登录方式 -->
      <!-- #ifdef APP-PLUS -->
      <view class="other-login-section">
        <view class="divider">
          <view class="divider-line"></view>
          <text class="divider-text">其他登录方式</text>
          <view class="divider-line"></view>
        </view>

        <view class="wechat-login-icon" @click="handleWechatLogin">
          <view class="wechat-icon-wrapper">
            <uni-icons type="weixin" size="24" color="#07c160"></uni-icons>
          </view>
        </view>
      </view>
      <!-- #endif -->
    </view>

    <!-- 底部版权信息 -->
    <view class="footer-section">
      <text class="copyright-text"
        >© 2025 HengTong Tech. All Rights Reserved.</text
      >
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from "vue";
import useLoginApi from "./api/login";
import type { ILoginParams } from "./api/interface";
import { ensureUserInfoStructure } from "@/utils/authFunction";

// 当前选中的标签
const currentTab = ref<"account" | "sms">("account");

// 加载状态
const accountLoading = ref(false);
const smsLoading = ref(false);
const smsLoginLoading = ref(false);
const countdown = ref(0);
let countdownTimer: any = null;

// 账号登录表单
const accountForm = reactive<ILoginParams>({
  Account: "",
  Password: "",
  Tenant: "",
});

// 短信登录表单
const smsForm = reactive({
  Mobile: "",
  Code: "",
});

// 验证账号登录表单
const validateAccountForm = () => {
  if (!accountForm.Account.trim()) {
    uni.showToast({
      title: "请输入用户名",
      icon: "none",
    });
    return false;
  }

  if (!accountForm.Password.trim()) {
    uni.showToast({
      title: "请输入密码",
      icon: "none",
    });
    return false;
  }

  if (accountForm.Password.length < 6 || accountForm.Password.length > 20) {
    uni.showToast({
      title: "密码长度在6-20个字符之间",
      icon: "none",
    });
    return false;
  }

  return true;
};

// 验证手机号
const validateMobile = (mobile: string) => {
  if (!mobile.trim()) {
    uni.showToast({
      title: "请输入手机号",
      icon: "none",
    });
    return false;
  }

  const mobileReg = /^1[3-9]\d{9}$/;
  if (!mobileReg.test(mobile)) {
    uni.showToast({
      title: "请输入正确的手机号",
      icon: "none",
    });
    return false;
  }

  return true;
};

// 验证短信登录表单
const validateSmsForm = () => {
  if (!validateMobile(smsForm.Mobile)) {
    return false;
  }

  if (!smsForm.Code.trim()) {
    uni.showToast({
      title: "请输入验证码",
      icon: "none",
    });
    return false;
  }

  if (smsForm.Code.length !== 6) {
    uni.showToast({
      title: "验证码为6位数字",
      icon: "none",
    });
    return false;
  }

  return true;
};

// 切换标签
const switchTab = (tab: "account" | "sms") => {
  currentTab.value = tab;
};

// 微信登录
const handleWechatLogin = async () => {
  try {
    const loginRes = await uni.login({
      provider: "weixin",
    });

    const res = await useLoginApi().wechatMiniProgramLogin({
      Code: loginRes.code,
    });

    if (res.Code === 200) {
      // 登录成功，保存token
      const expiresIn = res.Data.expires_in || 3600;
      const expireTime = Date.now() + expiresIn * 1000;

      uni.setStorageSync("token", res.Data.access_token);
      uni.setStorageSync("tokenExpireTime", expireTime);

      // 立即获取用户信息
      try {
        const userInfoRes = await useLoginApi().getUserInfo();

        // 使用工具函数确保用户信息结构完整
        const safeUserInfo = ensureUserInfoStructure(userInfoRes);

        uni.setStorageSync("userInfo", safeUserInfo);
      } catch (error) {
        console.error("获取用户信息异常:", error);
      }

      uni.switchTab({
        url: "/pages/work/work",
      });
    } else if (res.Code === 201) {
      // 微信未绑定的处理...
      const wechatKey =
        res.Data?.WechatBindKey ||
        res.Data?.wechatKey ||
        `wechat_${Date.now()}`;
      uni.setStorageSync("tempWechatKey", wechatKey);

      uni.redirectTo({
        url: `/pages/login/select?wechatKey=${wechatKey}`,
      });
    }
  } catch (error: any) {
    console.error("微信登录异常:", error);
    uni.showToast({
      title: `登录异常: ${error.message || JSON.stringify(error)}`,
      icon: "none",
      duration: 3000,
    });
  }
};

// 账号登录
const handleAccountLogin = async () => {
  if (!validateAccountForm()) return;

  try {
    accountLoading.value = true;
    const res = await useLoginApi().login(accountForm);

    if (res.Code === 200) {
      // 使用统一的登录成功处理函数
      await handleLoginSuccess(res.Data.access_token, res.Data.expires_in);
    } else {
      uni.showToast({
        title: res.Message || "登录失败",
        icon: "none",
      });
    }
  } catch (error: any) {
    console.error("账号登录失败:", error);
  } finally {
    accountLoading.value = false;
  }
};

// 发送短信验证码
const sendSms = async () => {
  if (!validateMobile(smsForm.Mobile)) return;

  try {
    smsLoading.value = true;

    const res = await useLoginApi().sendLoginSms({
      Mobile: smsForm.Mobile,
      Type: "login",
    });

    if (res.Code === 200) {
      uni.showToast({
        title: "验证码已发送",
        icon: "success",
      });

      // 开始倒计时
      countdown.value = 60;
      countdownTimer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(countdownTimer);
          countdownTimer = null;
        }
      }, 1000);
    } else {
      uni.showToast({
        title: res.Message || "发送验证码失败",
        icon: "none",
      });
    }
  } catch (error: any) {
    console.error("发送短信失败:", error);
  } finally {
    smsLoading.value = false;
  }
};

// 短信登录
const handleSmsLogin = async () => {
  if (!validateSmsForm()) return;

  try {
    smsLoginLoading.value = true;
    const res = await useLoginApi().loginBySms({
      Mobile: smsForm.Mobile,
      Code: smsForm.Code,
    });

    if (res.Code === 200) {
      // 使用统一的登录成功处理函数
      await handleLoginSuccess(res.Data.access_token, res.Data.expires_in);
    } else {
      uni.showToast({
        title: res.Message || "登录失败",
        icon: "none",
      });
    }
  } catch (error: any) {
    console.error("短信登录失败:", error);
  } finally {
    smsLoginLoading.value = false;
  }
};

// 登录成功处理函数
const handleLoginSuccess = async (token: string, expiresIn: number) => {
  // 1. 先存储token
  uni.setStorageSync("token", token);
  uni.setStorageSync(
    "tokenExpireTime",
    Date.now() + (expiresIn || 3600) * 1000,
  );

  // 2. 立即获取用户信息
  try {
    const userInfoRes = await useLoginApi().getUserInfo();

    // 保存用户信息到本地存储
    uni.setStorageSync("userInfo", userInfoRes);
  } catch (error) {
    console.error("获取用户信息异常:", error);
    // 即使获取用户信息失败，也不影响登录流程
  }

  uni.showToast({
    title: "登录成功",
    icon: "success",
  });

  // 3. 跳转到首页
  setTimeout(() => {
    uni.switchTab({
      url: "/pages/work/work",
    });
  }, 500);
};

// 页面加载时检查登录状态
onMounted(() => {
  const token = uni.getStorageSync("token");
  const tokenExpireTime = uni.getStorageSync("tokenExpireTime");

  // 如果存在有效的token，直接跳转到首页
  if (token && tokenExpireTime && Date.now() < tokenExpireTime) {
    uni.redirectTo({
      url: "/pages/work/work",
    });
  }
});

// 组件销毁时清除定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
    countdownTimer = null;
  }
});
</script>
<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
  padding-top: 70px;
  box-sizing: border-box;
}

// 背景装饰
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;

  .circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    animation: float 6s ease-in-out infinite;

    &.circle-1 {
      width: 120rpx;
      height: 120rpx;
      top: 15%;
      right: 10%;
      animation-delay: 0s;
    }

    &.circle-2 {
      width: 80rpx;
      height: 80rpx;
      top: 35%;
      left: 8%;
      animation-delay: 2s;
    }

    &.circle-3 {
      width: 160rpx;
      height: 160rpx;
      bottom: 20%;
      right: 15%;
      animation-delay: 4s;
    }
  }
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-20px) rotate(180deg);
  }
}

.header-section {
  padding: 60rpx 60rpx 60rpx;
  display: flex;
  justify-content: center;
  position: relative;
  z-index: 1;

  .brand-container {
    display: flex;
    flex-direction: column;
    align-items: center;

    .logo {
      width: 150rpx;
      height: 150rpx;
      margin-bottom: 24rpx;
    }

    .brand-name {
      font-size: 48rpx;
      font-weight: 700;
      color: #ffffff;
      text-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
      margin-bottom: 8rpx;
    }

    .brand-slogan {
      font-size: 26rpx;
      color: rgba(255, 255, 255, 0.8);
      text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
    }
  }
}

.main-content {
  flex: 1;
  padding: 0 40rpx;
  position: relative;
  z-index: 1;

  .tab-wrapper {
    margin-bottom: 40rpx;
    padding: 0 40rpx;

    .tab-header {
      display: flex;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 50rpx;
      padding: 8rpx;
      backdrop-filter: blur(10rpx);
      border: 1rpx solid rgba(255, 255, 255, 0.2);

      .tab-item {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8rpx;
        padding: 20rpx 0;
        border-radius: 42rpx;
        transition: all 0.3s ease;
        position: relative;
        z-index: 2;

        .tab-text {
          font-size: 26rpx;
          color: rgba(255, 255, 255, 0.7);
        }

        &.active {
          background: rgba(255, 255, 255, 0.2);
          backdrop-filter: blur(20rpx);
          box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);

          .tab-text {
            color: #ffffff;
            font-weight: 500;
          }
        }
      }
    }
  }

  .form-container {
    // 移除背景、阴影和边框
    padding: 50rpx 40rpx;

    .login-form {
      .input-group {
        margin-bottom: 32rpx;

        .glass-input {
          // 毛玻璃输入框样式
          background: rgba(255, 255, 255, 0.2);
          border: 1rpx solid rgba(255, 255, 255, 0.3);
          border-radius: 16rpx;
          backdrop-filter: blur(10rpx);
          height: 96rpx;
          transition: all 0.3s ease;

          :deep(.uni-easyinput__content) {
            background: transparent !important;
            border: none !important;
            height: 96rpx;
            padding: 0 24rpx !important;
          }

          :deep(.uni-easyinput__content-input) {
            font-size: 30rpx !important;
            color: #ffffff !important;
            height: 96rpx;

            &::placeholder {
              color: rgba(255, 255, 255, 0.6) !important;
            }
          }

          :deep(.uni-icons) {
            color: rgba(255, 255, 255, 0.8) !important;
          }

          &:focus-within {
            background: rgba(255, 255, 255, 0.25);
            border-color: rgba(255, 255, 255, 0.5);
            box-shadow: 0 0 0 4rpx rgba(255, 255, 255, 0.1);
          }
        }

        .sms-input-wrapper {
          display: flex;
          align-items: center;
          gap: 16rpx;

          .sms-input {
            flex: 1;
          }

          .sms-button {
            flex-shrink: 0;
            padding: 0 32rpx;
            height: 96rpx;
            background: rgba(255, 255, 255, 0.2);
            border: 1rpx solid rgba(255, 255, 255, 0.3);
            border-radius: 16rpx;
            backdrop-filter: blur(10rpx);
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;

            &:active {
              transform: scale(0.98);
            }

            .sms-button-text {
              font-size: 28rpx;
              color: #ffffff;
              font-weight: 500;
            }

            &.sms-button--disabled {
              background: rgba(255, 255, 255, 0.1);
              border-color: rgba(255, 255, 255, 0.2);

              .sms-button-text {
                color: rgba(255, 255, 255, 0.5);
              }
            }
          }
        }
      }

      .submit-section {
        margin-top: 50rpx;

        .primary-button {
          width: 100%;
          height: 96rpx;
          background: linear-gradient(
            135deg,
            rgba(60, 156, 255, 0.8),
            rgba(41, 121, 255, 0.8)
          );
          border: 1rpx solid rgba(255, 255, 255, 0.3);
          border-radius: 16rpx;
          backdrop-filter: blur(10rpx);
          display: flex;
          align-items: center;
          justify-content: center;
          position: relative;
          overflow: hidden;
          box-shadow: 0 8rpx 24rpx rgba(60, 156, 255, 0.3);
          transition: all 0.3s ease;

          &:active {
            transform: scale(0.98);
          }

          .button-text {
            font-size: 32rpx;
            color: #ffffff;
            font-weight: 600;
            position: relative;
            z-index: 1;
          }

          .button-shine {
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(
              90deg,
              transparent,
              rgba(255, 255, 255, 0.3),
              transparent
            );
            animation: buttonShine 2s infinite;
          }

          &.primary-button--loading {
            background: rgba(200, 201, 204, 0.6);
            box-shadow: none;

            .button-text {
              color: #ffffff;
            }
          }
        }
      }
    }
  }

  .other-login-section {
    margin-top: 60rpx;
    padding: 0 40rpx;

    .divider {
      display: flex;
      align-items: center;
      margin-bottom: 40rpx;

      .divider-line {
        flex: 1;
        height: 2rpx;
        background: rgba(255, 255, 255, 0.3);
      }

      .divider-text {
        padding: 0 24rpx;
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.7);
      }
    }

    .wechat-login-icon {
      display: flex;
      justify-content: center;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.95);
      }

      .wechat-icon-wrapper {
        width: 72rpx;
        height: 72rpx;
        background: rgba(255, 255, 255, 0.2);
        border: 1rpx solid rgba(255, 255, 255, 0.3);
        border-radius: 18rpx;
        backdrop-filter: blur(10rpx);
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
      }
    }
  }
}

@keyframes buttonShine {
  0% {
    left: -100%;
  }
  50% {
    left: 100%;
  }
  100% {
    left: 100%;
  }
}

.footer-section {
  padding: 40rpx 40rpx 20rpx;
  text-align: center;
  position: relative;
  z-index: 1;

  .copyright-text {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.6);
  }
}
</style>
